package club.itstudio.itouc.config

import club.itstudio.itouc.core.exception.SessionInvalid
import club.itstudio.itouc.service.JwOps
import org.aspectj.lang.ProceedingJoinPoint
import org.aspectj.lang.annotation.Around
import org.aspectj.lang.annotation.Aspect
import org.springframework.context.annotation.Configuration
import org.springframework.stereotype.Component
import org.springframework.web.context.request.RequestContextHolder
import org.springframework.web.context.request.ServletRequestAttributes

/**
 * 管理员配置
 */
@Configuration
class AdminConfig (
        val adminSet: MutableSet<String> = mutableSetOf("17020031002"),
        var timeStamp: Long = 0L
) {
    fun contains(userCode: String) = adminSet.contains(userCode)
}

/**
 * 管理员登录注解的实现
 */
@Aspect
@Component
class AdminRequiredHandler(val jwOps: JwOps,
                           val adminConfig: AdminConfig) {

    @Around("@annotation(club.itstudio.itouc.core.annotation.AdminRequired)")
    fun access(joinPoint: ProceedingJoinPoint): Any {
        val token = getToken()
        val session = jwOps.getJwSession(token)
        if (adminConfig.contains(session.userCode))
            return joinPoint.proceed()
        else
            throw SessionInvalid()
    }

    fun getToken(): String {
        val sra = RequestContextHolder.getRequestAttributes() as ServletRequestAttributes
        val cookies = sra.request.cookies
        if (cookies != null && cookies.isNotEmpty()) {
            cookies.forEach {
                if ("token" == it.name) {
                    return it.value
                }
            }
        }
        throw SessionInvalid()
    }
}